<template>
	<div>

		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>{{ title }}</el-breadcrumb-item>
		</el-breadcrumb>

		<el-form :model="ruleForm" :inline="false" ref="ruleForm" label-width="100px" class="demo-ruleForm">
			<el-form-item label="商品主图:">
				<Uploadimg :limit="10" :file-list="ruleForm.image" @getUrl="getUrl" @handleRemove="handleRemove">
				</Uploadimg>
			</el-form-item>
			<el-form-item label="商品名称:">
				<el-input v-model="ruleForm.goodsName"></el-input>
			</el-form-item>
			<el-form-item label="商品简介:">
				<el-input v-model="ruleForm.goodsInfo"></el-input>
			</el-form-item>
			<el-form-item label="关键词:">
				<el-tag :key="tag" v-for="tag in dynamicTags" closable :disable-transitions="false"
					@close="handleClosekey(tag)">
					{{ tag }}
				</el-tag>
				<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small"
					@keyup.enter.native="handleInputConfirmkey" @blur="handleInputConfirmkey">
				</el-input>
				<el-button v-else class="button-new-tag" size="small" @click="showInputkey">+ New Tag</el-button>
			</el-form-item>
			<!-- <el-form-item label="排序:">
				<el-input v-model="ruleForm.sort" placeholder="数值越大越靠前" type="number" min=0></el-input>
			</el-form-item> -->
			<!-- 规格 -->
			<el-divider></el-divider>
			<div>
				<div class="goods-spec">
					<h3>商品规格</h3>
					<el-link type="primary" @click="addPrivateSpec" class="goods-spec-add">添加规格</el-link>
				</div>
				<div class="goods-container" v-for="(attr, index) in items" :key="index">
					<div class="goods-content">
						<div class="goods-content-box">
							<div class="goods-content-left">
								<el-form label-width="80px" style="width:400px">
									<el-form-item label="规格名">
										<el-input v-model="attr.value" placeholder="请输入规格名"></el-input>
									</el-form-item>
									<el-form-item label="规格值">
										<el-tag v-for="tag in attr.detail" :key="tag" closable
											:disable-transitions="false" @close="handleClose(tag, attr)">
											{{ tag }}
										</el-tag>
										<el-input class="input-new-tag" v-if="attr.inputVisible"
											v-model="attr.inputValue" :ref="`saveTagInput${index}`" size="small"
											@keyup.enter.native="handleInputConfirm(attr.inputValue, attr)"
											@blur="handleInputConfirm(attr.inputValue, attr)">
										</el-input>
										<el-button v-else class="button-new-tag" size="small"
											@click="showInput(attr, index)">+ 添加</el-button>
									</el-form-item>
								</el-form>
							</div>
							<div class="goods-content-right">
								<el-link type="danger" @click="delPrivateSpec(index)">删除规格</el-link>
							</div>
						</div>
					</div>
				</div>

				<p style="margin:24px 0 10px 0">规格与库存</p>
				<el-table ref="multipleTable" :data="tableColumnList.tableBodyList" stripe tooltip-effect="dark"
					style="width: 100%;margin-top:1%;">
					<el-table-column :label="item.propName" :property="item.prop"
						v-for="item in tableColumnList.tableHeaderList" :key="item.prop" align="center">
						<template slot-scope="scope">
							<span>{{ scope.row[scope.column.property] }}</span>
						</template>
					</el-table-column>
					<el-table-column label="库存">
						<template slot-scope="scope">
							<el-input v-model.number="scope.row.stock"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="售卖价(元)">
						<template slot-scope="scope">
							<el-input v-model.number="scope.row.price"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="成本价(元)">
						<template slot-scope="scope">
							<el-input v-model.number="scope.row.cost"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="原价(元)">
						<template slot-scope="scope">
							<el-input v-model.number="scope.row.otPrice"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="规格编码">
						<template slot-scope="scope">
							<el-input v-model="scope.row.skuCode"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="商品编码">
						<template slot-scope="scope">
							<el-input v-model="scope.row.barCode"></el-input>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<el-footer>
				<el-button type="primary" style="width: 20%;margin-bottom: 10%; margin-left: 30%;margin-top: 120px;"
					@click="submit">提交并上架
				</el-button>
			</el-footer>

		</el-form>
	</div>
</template>
 
<script>
import Uploadimg from "@/components/Uploadimg";
import { resolve } from "q";
import { saveGoods, goodsDescById, getImg } from '../../api/EcommerceManagement'

export default {
	data() {
		return {
			ruleForm: {
				image: [],
				goodsName: '',
				goodsInfo: '',
			},
			imageList: [],
			dynamicTags: ['标签一', '标签二'],  //关键词
			inputVisible: false,
			inputValue: '',
			tableColumnList: {
				tableHeaderList: [],
				tableBodyList: [
					{

					}
				]
			},
			items: [    //sku属性
				{
					value: '', //规格名
					detail: [], //规格值数组
					inputVisible: false,
					inputValue: ''
				}
			],
			options: [],   //商品类列表
			id: "",   //无则添加有则编辑
			timer: '',  //刷新子组件
			title: "",
		}
	},
	mounted() {
		this.title = "添加商品"
		if (this.$route.query.id) {
			this.id = this.$route.query.id;
			this.title = "商品信息"
			this.getdetails();
		}
	},
	computed: {
		// 计算规格
		calculateAttribute() {
			// 初始化
			let obj = {}
			this.items.forEach((item) => {
				// 判断有没有输入规格名
				if (item.value) {
					//规格名:规格值     //'颜色':'尺寸'
					obj[item.value] = item.detail
				}
			})
			return obj
		}
	},
	watch: {
		// 监听规格数据
		calculateAttribute(newVal) {
			// if(!this.ruleForm.specType){return;}
			// this.attribute(newVal);
			let cloneNewVal = JSON.parse(JSON.stringify(newVal))
			let attrName = [] //规格名数组
			let attrValue = [] //规格值数组
			for (let key in cloneNewVal) {
				attrName.push(key)
				attrValue.push(cloneNewVal[key])
			}

			// 表格内容数据（笛卡尔积算法）
			let finalArr = this.cartesianProductOf(...attrValue)

			let tableObj = {
				tableBodyList: [],
				tableHeaderList: []
			}
			// 表格内容
			tableObj.tableBodyList = finalArr.map((item) => {
				let obj = {
					stock: 0,	   //库存
					cost: 0,        //成本
					otPrice: 0,     //原价
					price: 0,       //售卖价
					barCode: '',   //商品条码
					skuCode: '',   //sku条码	
				}
				for (let i = 0; i < item.length; i++) {
					obj[attrName[i]] = item[i]
				}
				return obj
			})
			this.tableColumnList.tableBodyList = tableObj.tableBodyList //表格内容数据

			// 表头
			let skuTableArr = Object.keys(newVal)
			tableObj.tableHeaderList = skuTableArr.map((item) => {
				return {
					prop: item,
					propName: item
				}
			})
			this.tableColumnList.tableHeaderList = tableObj.tableHeaderList // 表头
		},
		'ruleForm.specType': {
			deep: true,
			handler: function (newV, oldV) {
				if (!newV) {
					this.tableColumnList = this.$options.data().tableColumnList;
					this.items = this.$options.data().items;
				}
			}
		}
	},
	methods: {
		getUrl(getUrl) {
			let imgPath = getUrl;
			this.imageList.push(imgPath)
		},
		handleRemove(url) {
			let imgUrl = url;
			this.imageList.splice(this.imageList.findIndex(item => item === imgUrl), 1)
		},
		getpositionName() {
			const info = this.$refs.myCascader.getCheckedNodes()[0];
			this.ruleForm.cateName = info.label;
		},
		removeEmptyChildren(node) {   //杀生
			var that = this;
			node.forEach(item => {
				if ('children' in item && item.children.length === 0) {
					delete item.children
				} else if ('children' in item && item.children.length) {
					that.removeEmptyChildren(item.children)
				}
			})
			return node;
		},
		attribute(newVal) {
			var that = this;
			// 	this.$api.goodssku(that.items).then(res=>{
			// 		if(res.code==0){
			// 			// console.log("属性",res);
			// 			let cloneNewVal = JSON.parse(JSON.stringify(newVal))
			// 			let attrName = [] //规格名数组
			// 			let attrValue = [] //规格值数组
			// 			for (let key in cloneNewVal) {
			// 			  attrName.push(key)
			// 			  attrValue.push(cloneNewVal[key])
			// 			}

			// 			// 表格内容数据（笛卡尔积算法）
			// 			let finalArr = this.cartesianProductOf(...attrValue)	
			// 			let tableObj = {
			// 			  tableBodyList: [],
			// 			  tableHeaderList: []
			// 			}
			// 			// 表格内容
			// 			tableObj.tableBodyList = res.data.map((item) => {
			// 			  var detail=item.detail;
			// 			  return Object.assign(item, detail);
			// 			})
			// 			this.tableColumnList.tableBodyList = tableObj.tableBodyList //表格内容数据
			// 			this.tableColumnList.tableBodyList = res.data;
			// 			// 表头
			// 			let skuTableArr = Object.keys(newVal)
			// 			tableObj.tableHeaderList = skuTableArr.map((item) => {
			// 			  return {
			// 			    prop: item,
			// 			    propName: item
			// 			  }
			// 			})
			// 			this.tableColumnList.tableHeaderList = tableObj.tableHeaderList // 表头
			// 		}else{
			// 			this.$message({
			// 				 message: res.message,
			// 				 center: true,
			// 			});
			// 		}
			// 	}).catch(err=>{console.log("网络错误",err)})
		},
		goBack() {
			this.$router.go(-1);
		},
		//关键词操作
		handleClosekey(tag) {
			this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
		},

		showInputkey() {
			this.inputVisible = true;
			this.$nextTick(_ => {
				this.$refs.saveTagInput.$refs.input.focus();
			});
		},
		handleInputConfirmkey() {
			let inputValue = this.inputValue;
			if (inputValue) {
				this.dynamicTags.push(inputValue);
			}
			this.inputVisible = false;
			this.inputValue = '';
		},
		//获取详情
		getdetails() {
			var that = this;
			goodsDescById({ id: that.id }).then(res => {
				console.log(JSON.stringify(res))
				that.ruleForm.goodsName = res.goodsName
				that.ruleForm.goodsInfo = res.goodsInfo
				let imgArr = res.sliderImage.split(",");
				for (let itempath of imgArr) {
					itempath = itempath.replace(/\s/g,"");
					if (itempath != undefined && itempath != "" && itempath != null) {
						let imgparam = {
							imgPath: itempath
						}
						getImg(imgparam).then(res => {
							const myBlob = new window.Blob([res.data], { type: 'image/jpeg' })
							const imageUrl = window.URL.createObjectURL(myBlob)
							let imgparam = {
								name: itempath,
								url: imageUrl
							}
							that.ruleForm.image.push(imgparam);
						})
					}
				}
				that.dynamicTags = res.keyword.split(",");
				let items = JSON.parse(res.items);
				let attrs = JSON.parse(res.attrs);
				that.items = items.map(item => {
					item.inputValue = "";
					item.inputVisible = false;
					return item;
				})
				setTimeout(() => {
					let tablearr = [];
					for (var i = 0; i < attrs.length; i++) {
						tablearr.push(Object.assign(that.tableColumnList.tableBodyList[i], attrs[i]));
					}
					that.tableColumnList.tableBodyList = tablearr;
				}, 500)
				that.timer = new Date().getTime();
			}).catch(err => { console.log("网络错误", err) })
		},

		blobToBase64(blob) {
			return new Promise((resolve, reject) => {
				const fileReader = new FileReader();
				fileReader.onload = (e) => {
					resolve(e.target.result);
				};
				fileReader.readAsDataURL(blob);
				fileReader.onerror = () => {
					reject(new Error('文件流异常'))
				}
			})
		},
		submit() {
			var that = this;
			var obj;
			if (this.id) {  //编辑
				obj = JSON.parse(JSON.stringify(that.ruleForm));
				obj.id = that.id;
				obj.items = that.items;
				obj.attrs = that.tableColumnList.tableBodyList;
				obj.keyword = that.dynamicTags.toString();
				obj.sliderImage = that.imageList.toString();
				this.$api.goodsedit(obj).then(res => {
					if (res.code == 0) {
						this.$message({
							type: "success",
							message: res.message,
							center: true,
						});
						that.$router.push({ path: '/product/goods' })
					} else {
						this.$message({
							message: res.message,
							center: true,
						});
					}
				}).catch(err => { console.log("网络错误", err) })
			} else {
				obj = JSON.parse(JSON.stringify(that.ruleForm));

				obj.items = JSON.stringify(that.items);
				obj.attrs = JSON.stringify(that.tableColumnList.tableBodyList);
				obj.keyword = that.dynamicTags.toString();
				obj.sliderImage = that.imageList.toString();
				console.log(JSON.stringify(obj))
				saveGoods(obj).then(res => {
					if (res.code == 0) {
						this.$message({
							type: "success",
							message: res.message,
							center: true,
						});
						// that.$router.push({ path: '/product/goods' })
					} else {
						this.$message({
							message: res.message,
							center: true,
						});
					}
				}).catch(err => { console.log("网络错误", err) })
			}
		},
		/*****规格*****/
		// 添加规格
		addPrivateSpec(index) {
			this.items.push({
				value: '',
				detail: [],
				inputVisible: false,
				inputValue: ''
			})
		},
		delPrivateSpec(index) {
			this.items.splice(index, 1)
		},
		handleInputConfirm(val, attr) {
			if (val) {
				attr.detail.push(val)
			}
			attr.inputVisible = false
			attr.inputValue = ''
		},
		handleClose(tag, item) {
			item.detail.splice(item.detail.indexOf(tag), 1)
		},
		showInput(attr, index) {
			attr.inputVisible = true
			this.$nextTick((_) => {
				this.$refs[`saveTagInput${index}`][0].$refs.input.focus()
			})
		},
		// 笛卡尔积算法
		cartesianProductOf(...args) {
			return args.reduce(
				(total, current) => {
					let ret = []
					total.forEach((a) => {
						current.forEach((b) => {
							ret.push(a.concat([b]))
						})
					})
					return ret
				},
				[[]]
			)
		}

	},
	components: {
		Uploadimg: Uploadimg,
	}
};
</script>
<style scoped>
.demo-ruleForm {
	margin-top: 20px;
}

.demo-ruleForm>div {
	width: 80%;
}

.el-tag+.el-tag {
	margin-left: 10px;
}

.button-new-tag {
	margin-left: 10px;
	height: 32px;
	line-height: 30px;
	padding-top: 0;
	padding-bottom: 0;
}

.input-new-tag {
	width: 90px;
	margin-left: 10px;
	vertical-align: bottom;
}

.goods-spec {
	display: flex;
	justify-content: space-between;
	margin-bottom: 10px;
}

.goods-spec .goods-spec-add {
	margin-right: 15px;
}

.goods-container .button-new-tag {
	height: 32px;
	line-height: 30px;
	padding-top: 0;
	padding-bottom: 0;
}

.goods-container .input-new-tag {
	width: 90px;
	margin-right: 10px;
	vertical-align: bottom;
}

.goods-container .el-tag {
	margin-right: 10px;
}

.goods-container .goods-content {
	margin-bottom: 10px;
	padding: 14px;
	border: 1px solid #ebeef5;
	border-radius: 4px;
	background-color: #fcfcfc;
}

.goods-content .goods-content-box {
	display: flex;
	align-items: center;
}

.goods-content-box .goods-content-left {
	flex: 1;
}

el-footer {
	display: flex;
	height: 4vh;
	width: 100%;
	align-items: center;
}
</style>